﻿using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Collections.ObjectModel;
using AdminModule.CommonClasses;
using System.Collections.Generic;

namespace AdminModule.IndexMarkServiceReference
{
    public partial class DTOChilds
    {
        public DTOChilds()
        {
            this.Childs = new ObservableCollection<DTOBase>();
        }

        /// <summary>
        /// Флаг, позволяющий избежать повторной подписки на событие CollectionChanged у коллекции Childs
        /// </summary>
        private bool EventHandlerSet = false;

        public ObservableCollection<DTOBase> Childs2
        {
            get
            {
                if (Childs == null) Childs = new ObservableCollection<DTOBase>();
                if (this.EventHandlerSet == false)
                {
                    Childs.CollectionChanged += new System.Collections.Specialized.NotifyCollectionChangedEventHandler(Childs_CollectionChanged);
                    EventHandlerSet = true;
                }
                if (ChildsCount > 0 && Childs.Count == 0)
                    return new ObservableCollection<DTOBase> { new DTOBase { IsVisibility = false } };
                else
                   return Childs;
            }
            set
            {
                Childs = value;
            }
        }

        void Childs_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
        {
            this.RaisePropertyChanged("Childs2");
        }

        /// <summary>
        /// Удаляет неотмеченные дочерние элементы
        /// </summary>
        public void ExcludeUnchekedItems()
        {
            _ExcludeUnchekedItems(this);
        }

        private void _ExcludeUnchekedItems(DTOChilds obj)
        {
            List<DTOBase> objectsForDelete = new List<DTOBase>();
            foreach (DTOBase el in obj.Childs)
            {
                if (el.Checked == true)
                {
                    if (el is DTOChilds) _ExcludeUnchekedItems(el as DTOChilds);
                }
                else
                {
                    objectsForDelete.Add(el);
                }
            }
            foreach (DTOBase el in objectsForDelete) { obj.Childs.Remove(el); }
        }
    }
}
